<script setup>

import { addLogisticsCompanyApi, updateLogisticsCompanyApi } from '@/api/logisticsCompany';
import { ElMessage } from 'element-plus';
import { getCurrentInstance, onMounted, ref } from 'vue';


//获取当前Vue实例
const instance = getCurrentInstance()
const ruleFormRef = ref(null)
const dialogFormVisible = ref(false)
const title = ref('')
const companyForm = ref({
    id: '',
    companyName: '',
    minPrice: '',
    linkUser: '',
    linkPhone: '',
})

const reset = () => {
    companyForm.value = {
        id: '',
        companyName: '',
        minPrice: '',
        linkUser: '',
        linkPhone: '',
    }
}

const save =async () => {
     if (!ruleFormRef) return
    await ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            let res = null
            if (companyForm.value.id) {
                res = await updateLogisticsCompanyApi(companyForm.value)
            }else {
                res = await addLogisticsCompanyApi(companyForm.value)
            }
            if (res.code == 1) {
                ElMessage.success('操作成功')
                dialogFormVisible.value = false
                instance.emit('refresh')
            }else{
                ElMessage.error('操作失败')
            }
        } else {
        console.log('error submit!', fields)
        }
    })
}


const rules = ref({
  companyName: [
    { required: true, message: '名字不能为空', trigger: 'blur' }
  ],
})


defineExpose({
    dialogFormVisible,
    title,
    companyForm,
    reset,
})

</script>

<template>
    <el-dialog style="width: 400px;" v-model="dialogFormVisible" :title="title">
    <el-form :model="companyForm" :rules="rules" ref="ruleFormRef" label-width="auto">
      <el-form-item label="物流公司名字" placeholder="请输入" prop="companyName" >
        <el-input v-model="companyForm.companyName" />
      </el-form-item>
      <el-form-item label="最低费用" placeholder="请输入" >
        <el-input v-model="companyForm.minPrice" />
      </el-form-item>
      <el-form-item label="联系人" placeholder="请输入" >
        <el-input v-model="companyForm.linkUser" />
      </el-form-item>
      <el-form-item label="联系电话" placeholder="请输入" >
        <el-input v-model="companyForm.linkPhone" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>